import { _decorator, Component, EventTouch, Input, UITransform, Vec2, Vec3 } from 'cc';
import { Block } from './Block';
import { GameState } from './GameState';
import { LayerRoot } from './LayerRoot';
const { ccclass, property } = _decorator;

@ccclass('Layer2')
export class Layer2 extends Component {
    curBlock:Block = null;
    start() {
        if(GameState.gameMode === 1){
            return;
        }
        this.node.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    getBlockByPosition(worldPosition: Vec3):Block {
        const position = this.node.getComponent(UITransform).convertToNodeSpaceAR(worldPosition);
        let curBlock;
        for(let i = this.node.children.length - 1; i >= 0; i--){
            const block = this.node.children[i];
            if(!block.active) continue;
            const blockScript = block.getComponent(Block);
            if(!blockScript.canTouch) continue;
            if(block.getComponent(UITransform).getBoundingBox().contains(new Vec2(position.x, position.y))){
                curBlock = blockScript;
                break;
            }
        }
        return curBlock;
    }

    onTouchStart(e: EventTouch) {
        const position = e.getUILocation();
        const block = this.getBlockByPosition(new Vec3(position.x, position.y));
        this.curBlock = block;
        if(this.curBlock){
            if(!this.curBlock.node.active) return;
            block.playStartTouch();
        }
    }

    onTouchEnd(e: EventTouch) {
        if(this.curBlock){
            if(!this.curBlock.node.active) return;
            this.curBlock.payEndTouch();
            this.curBlock.setTmpPosition(this.curBlock.node.getWorldPosition())
            this.node.parent.getComponent(LayerRoot).moveBlockBack(this.curBlock);
            this.node.parent.getComponent(LayerRoot).playAudio(0);
        }
    }

    onTouchCancel(e: EventTouch) {
        if(this.curBlock){
            if(!this.curBlock.node.active) return;
            this.curBlock.payEndTouch();
            this.curBlock.setTmpPosition(this.curBlock.node.getWorldPosition())
            this.node.parent.getComponent(LayerRoot).moveBlockBack(this.curBlock);
        }
    }

    protected onDestroy(): void {
        this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Input.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }
    getBlockSize() {
        return this.node.children.length;
    }

    getZero(): Vec3 {
        return this.node.getComponent(UITransform).convertToWorldSpaceAR(new Vec3(0, 0, 0));
    }

    addBlock(block: Block) {
        block.node.setPosition(0, 0);
        block.node.setParent(this.node);
    }
}


